/**
 * @author yxw
 * date : 2013年10月30日 下午3:49:24
 */
package com.tzinfo.tzt.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.BDNotifyListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.galhttprequest.GalHttpRequest;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.ConvertSwitch;
import com.tzinfo.tzt.activity.util.MarkerTools;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FilterConfig;
import com.tzinfo.tzt.domain.LocationGeocoder;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.OldhouseVillageMap;
import com.tzinfo.tzt.util.CacheManager;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OldHouseMapActivity extends BaseActivity implements
        OnClickListener {

    // 百度组件
    private MapView mMapView = null; // 百度地图view
    private MapController mMapController = null;// 控制器
    private GeoPoint locationPoint = null;// 坐标点
    private MKMapViewListener mMapListener = null;// 百度地图缩放监听
    private OverlaySmall overlaySmall = null;// 自定义覆盖物
    private BMapManager mBMapManager = null;// 百度地图管理器
    // 定位相关
    private LocationClient mLocClient = null;// 定位器
    public MyLocationListenner myListener = new MyLocationListenner();// 定位监听
    private LocationData locData = null;// 当前位置信息
    private MyLocationOverlay myLocationOverlay = null;// 我的位置覆盖物
    private boolean isRequestLocation = false;
    protected LocationGeocoder geocoder;// 坐标对应地区内容

    // 存放所有房子的id的list
    private List<Integer> villageId = null;
    private List<String> villageName = null;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            // Toast.makeText(HouseMapActivity.this, "msg:" + msg.what,
            // Toast.LENGTH_SHORT).show();
        }

        ;
    };

    // UI组件
    private EditText searchEditText = null;
    private Button backBtn = null;
    private ImageView locationImage = null;
    private TextView[] overlayCircleView = new TextView[FilterConfig.ZUO_BIAO.length];

    // 数据
    private MyResultList oldhouseVillageMap = null;
    private String[] cacheJson = new String[9];

    // 标志
    static boolean isFinish = true;
    private boolean isNeedToSmall = true;
    private int tabNum = 0;

    // 全局变量
    final static double changeZoom = 14; // 显示房子位置的放大级数
    final static String baseUrl = AppDataConfig.oldUrl
            + AppDataConfig.OldhouseVillageMap;

    // 变量
    private int searchLocationId = -1;
    private double searchLat = 0;
    private double searchLng = 0;
    private int lat = 0;
    private int lng = 0;
    public static OldHouseMapActivity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        isFinish = false;
        // 初始化Application 需要在AndroidManifest.xml文件中配置
        // 1.初始化MBMapManager 地图管理类 这个必须放在setContentView()之前
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(getApplicationContext());
            mBMapManager.init(MyApplication.strKey,
                    new MyApplication.MyGeneralListener());
        }
        // 2.加载布局文件
        setContentView(R.layout.activity_house_map);
        setTitle();
        // 3.初始化视图
        initMapView();
        addBigView();

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mMapView.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        cacheJson = null;
        if (null!=mMapView)
        {
            mMapView.destroyDrawingCache();
        }
        if (mBMapManager != null) {
            mBMapManager = null;
        }
        mMapView = null;
        mMapController = null;
        locationPoint = null;
        mLocClient = null;
        myListener = null;
        locData = null;
        myLocationOverlay = null;
        geocoder = null;
        villageId = null;
        villageName = null;
        mHandler = null;
        mMapListener = null;
        searchEditText = null;
        backBtn = null;
        locationImage = null;
        overlayCircleView = null;
        oldhouseVillageMap = null;
        overlaySmall = null;
        System.gc();
        super.onDestroy();
    }

    private void setTitle() {
        searchEditText = (EditText) this.findViewById(R.id.et_search_top);
        searchEditText.setOnClickListener(this);
        Intent thisiIntent = getIntent();
        tabNum = thisiIntent.getIntExtra("tabNum", 0);
        searchEditText.setHint("搜索二手房");
    }

    private void initMapView() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressbar_loding);
        for (int i = 0; i < overlayCircleView.length; i++) {
            overlayCircleView[i] = (TextView) getLayoutInflater().inflate(
                    R.layout.overlay_circle, null);
            overlayCircleView[i]
                    .setOnClickListener(new MyOnClickListener(i + 1));
        }
        backBtn = (Button) this.findViewById(R.id.bt_back);
        backBtn.setOnClickListener(this);

        mMapView = (MapView) findViewById(R.id.bmapView);// 得到地图视图控件
        mMapController = mMapView.getController();// 初始化控制类
        mMapView.setLongClickable(true);

        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(5000);
        mLocClient.setLocOption(option);
        mLocClient.start();

        // mMapController.setMapClickEnable(true);
        // mMapView.setSatellite(false);
        // 初始化地图显示事件监听器，该接口监听地图显示事件，用户需要实现该接口以处理相应事件。
        mMapListener = new MKMapViewListener() {

            @Override
            public void onMapMoveFinish() {
                // 在此处理地图移动完成消息回调
                Log.wtf("onMapMoveFinish", mMapView.getZoomLevel() + "");
                changeViewSize();
            }

            @Override
            public void onMapAnimationFinish() {
                // 在此处理地图动画完成回调
                Log.wtf("onMapAnimationFinish", mMapView.getZoomLevel() + "");
                changeViewSize();
            }

            @Override
            public void onClickMapPoi(MapPoi mapPoiInfo) {
                // 点击到地图可点标注时会回调此接口
                String title = "";
                if (mapPoiInfo != null) {
                    title = mapPoiInfo.strText;
                    Toast.makeText(OldHouseMapActivity.this, title,
                            Toast.LENGTH_SHORT).show();
                    mMapController.animateTo(mapPoiInfo.geoPt);
                }
            }

            @Override
            public void onGetCurrentMap(Bitmap b) {

                // 截图成功后会回调此接口，回调图片数据，保存在"/mnt/sdcard/test"目录下
                Log.d("test", "test" + "onGetCurrentMap");
                File file = new File("/mnt/sdcard/test.png");
                FileOutputStream out;
                try {
                    out = new FileOutputStream(file);
                    if (b.compress(Bitmap.CompressFormat.PNG, 70, out)) {
                        out.flush();
                        out.close();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onMapLoadFinish() {
                // TODO Auto-generated method stub

            }
        };

        mMapController.enableClick(true);
        mMapController.setZoom(12);// 设置缩放比例
        // 用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)

        setCenter(MyApplication.locationCode);
        mMapView.setBuiltInZoomControls(true);// 设置内置缩放按钮
        // mMapView.displayZoomControls(true);// 设置缩放按钮可见
        // mMapView.setTraffic(true);//设置是否打开路况图
        // mMapView.setSatellite(true);//设置是否打开卫星图
        mMapView.setDoubleClickZooming(true);// 允许双击改变缩放比例
        mMapView.setOnTouchListener(null);// 设置触摸监听事件

        // 用户注册地图监听器
        mMapView.regMapViewListener(mBMapManager, mMapListener);
        mMapView.getOverlays().clear();
        myLocationOverlay = new MyLocationOverlay(mMapView);
        locData = new LocationData();
        myLocationOverlay.setData(locData);
        mMapView.getOverlays().add(myLocationOverlay);
        myLocationOverlay.enableCompass();
        mMapView.refresh();
        locationImage = (ImageView) this.findViewById(R.id.img_my_local);
        locationImage.setOnClickListener(this);
    }

    private void changeViewSize() {
        if (mMapView.getZoomLevel() >= changeZoom && isNeedToSmall) {
            removeAllCircleView();
            addSmallViewThread();
            isNeedToSmall = false;
        } else if (mMapView.getZoomLevel() < changeZoom && !isNeedToSmall) {
            removeAllView();
            addBigView();
            isNeedToSmall = true;
        }
    }

    private void setCenter(int locationCode) {
        if (locationCode == -1) {
            lat = (int) (MyApplication.location.getLatitude() * 1E6);
            lng = (int) (MyApplication.location.getLongitude() * 1E6);

        } else if (locationCode == 0) {
            lng = (int) (FilterConfig.ZUO_BIAO[0][0] * 1E6);
            lat = (int) (FilterConfig.ZUO_BIAO[0][1] * 1E6);
        } else {
            lng = (int) (FilterConfig.ZUO_BIAO[locationCode - 1][0] * 1E6);
            lat = (int) (FilterConfig.ZUO_BIAO[locationCode - 1][1] * 1E6);
        }
        locationPoint = new GeoPoint(lat, lng);
        mMapController.setCenter(locationPoint); // 设置地图中心点 不设置默认为天安门
        mMapView.refresh();
    }

    public void testUpdateClick() {
        isRequestLocation = true;
        mLocClient.requestLocation();
    }

    /**
     * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            if (MyApplication.location == null) {
                MyApplication.location = new Location("gps");
                MyApplication.location.setLatitude(location.getLatitude());
                MyApplication.location.setLongitude(location.getLongitude());
            }
            if (isRequestLocation) {
                locData.latitude = location.getLatitude();
                locData.longitude = location.getLongitude();
                locData.accuracy = location.getRadius();
                locData.direction = location.getDerect();
                myLocationOverlay.setData(locData);
                mMapView.refresh();
                mMapController.animateTo(new GeoPoint(
                        (int) (locData.latitude * 1e6),
                        (int) (locData.longitude * 1e6)), mHandler
                        .obtainMessage(1));
                isRequestLocation = false;
            }

        }

        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null) {
                return;
            }
        }
    }

    public class NotifyLister extends BDNotifyListener {
        public void onNotify(BDLocation mlocation, float distance) {
        }
    }

    private void removeAllCircleView() {
        for (int i = 0; i < overlayCircleView.length; i++) {
            mMapView.removeView(overlayCircleView[i]);
        }
    }

    private void removeAllView() {
        if (mMapView.getOverlays() != null && mMapView.getOverlays().size() > 0) {
            mMapView.getOverlays().clear();
        }
        if (mMapView != null && mMapView.getOverlays() != null) {
            mMapView.getOverlays().add(myLocationOverlay);
        }
        myLocationOverlay.enableCompass();
    }

    private void addBigView() {

        /**
         * 在想要添加Overlay的地方使用以下代码， 比如Activity的onCreate()中
         */
        // 准备overlay图像数据，根据实情情况修复
        Drawable mark = getResources().getDrawable(R.drawable.circle_bg);
        // 创建IteminizedOverlay
        OverlayBig overlayBig = new OverlayBig(mark, mMapView);

        Bitmap imgMarker = BitmapFactory.decodeResource(getResources(),
                R.drawable.circle_bg);

        int textSize = 30;
        if (MyApplication.widthPixels > 480) {
            textSize = 35;
        } else if (MyApplication.widthPixels == 480) {
            textSize = 30;
        } else {
            textSize = 25;
        }
        for (int i = 0; i < FilterConfig.ZUO_BIAO.length; i++) {

            GeoPoint point = ConvertSwitch.Convert_GCJ02_To_BD09_GeoPoint(
                    FilterConfig.ZUO_BIAO[i][1],
                    FilterConfig.ZUO_BIAO[i][0]);
            // 用OverlayItem准备Overlay数据
            OverlayItem item = new OverlayItem(point, "item" + i, "item1" + i);
            //原本overlayitem为底部中间对齐，现对其进行修正，中间对齐
            GeoPoint tempPoint = item.getPoint();
            tempPoint.setLatitudeE6(tempPoint.getLatitudeE6() - 30000);
            item.setGeoPoint(tempPoint);

            String name = FilterConfig.FILTER_AREA[i + 1];
            item.setMarker(MarkerTools.drawTextAtBitmap(imgMarker, name,
                    textSize));
            overlayBig.addItem(item);
        }
        removeAllView();
        mMapView.getOverlays().add(overlayBig);
        mMapView.refresh();
        System.gc();

    }

    private void addSmallViewThread() {
        GeoPoint centerPoint = mMapView.getMapCenter();// 地图中心坐标
        searchLat = ((double) centerPoint.getLatitudeE6()) / 1E6;
        searchLng = ((double) centerPoint.getLongitudeE6()) / 1E6;
        showProgressBar();
        new Thread(getLocationAddressRun).start();
    }

    private void getSearchLocationId() {
        searchLocationId = 0;
        Log.wtf("geocoder.getDistrict()", geocoder.getDistrict());
        String district = geocoder.getDistrict();
        if (district != null && district.length() > 0) {
            district = district.substring(0, district.length() - 1);
        }

        while (searchLocationId < FilterConfig.FILTER_CONTENT[0].length
                && !district
                .equals(FilterConfig.FILTER_CONTENT[0][searchLocationId])) {
            searchLocationId++;
        }
        if (searchLocationId == FilterConfig.FILTER_CONTENT[0].length) {
            searchLocationId = 0;
        }

        new Thread(getCacheResultRun).start();
    }

    private void addSmallView() {
        /**
         * 在想要添加Overlay的地方使用以下代码， 比如Activity的onCreate()中
         */
        // 准备overlay图像数据，根据实情情况修复
        Drawable mark = getResources().getDrawable(R.drawable.map_dialog);
        // 创建IteminizedOverlay
        overlaySmall = new OverlaySmall(mark, mMapView);

        Bitmap imgMarker = BitmapFactory.decodeResource(getResources(),
                R.drawable.map_dialog);
        List<Object> list = oldhouseVillageMap.getData();

        villageId = new ArrayList<Integer>();// 用于保存房子id
        villageName = new ArrayList<String>();// 用于保存房子name

        int textSize = 20;
        if (MyApplication.widthPixels > 480) {
            textSize = 25;
        } else if (MyApplication.widthPixels == 480) {
            textSize = 20;
        } else {
            textSize = 15;
        }
        for (int i = 0; i < list.size(); i++) {
            OldhouseVillageMap villageMap = (OldhouseVillageMap) list.get(i);
            // 讲id先保存
            GeoPoint point = ConvertSwitch.Convert_GCJ02_To_BD09_GeoPoint(villageMap.getLat(),villageMap.getLon());
            // 用OverlayItem准备Overlay数据
            OverlayItem item = new OverlayItem(point, "item" + i, "item1" + i);
            String name = villageMap.getName();
            if (name.length() > 5) {
                name = name.substring(0, 4) + "…";
            }
            String text = name + "：";
            // 小区房源数与实际不符合！
            if ("0".equals(villageMap.getHouseCount())) {
                text = "没有房子";
            } else {
                villageId.add(villageMap.getID());
                villageName.add(villageMap.getName());
                text += villageMap.getHouseCount();
                item.setMarker(MarkerTools.drawTextAtBitmap(imgMarker, text,
                        textSize));
                overlaySmall.addItem(item);
            }

        }
        removeAllView();
        Log.e("yxw", "removeAllView---" + new Date().toLocaleString());
        mMapView.getOverlays().add(overlaySmall);
        Log.e("yxw", "getOverlays---" + new Date().toLocaleString());
        mMapView.refresh();
        System.gc();
    }

    class MyOnClickListener implements OnClickListener {
        int locationCode = 0;

        public MyOnClickListener(int locationCode) {
            this.locationCode = locationCode;
        }

        @Override
        public void onClick(View v) {
            // 这里通过locationCode放大地图并读取信息
            isNeedToSmall = false;
            removeAllCircleView();
            setCenter(locationCode);
            mMapView.getController().setZoom(16);
            searchLocationId = locationCode;
            showProgressBar();
            new Thread(getCacheResultRun).start();
            mMapView.refresh();
        }

    }

    protected void getDataError(String ERRORMESSAGE) {
        if (isFinish) {

            new AlertDialog.Builder(OldHouseMapActivity.this)
                    .setCancelable(false).setMessage(ERRORMESSAGE)
                    .setPositiveButton(getResources().getString

                            (R.string.cancel), new DialogInterface.OnClickListener()

                    {
                        public void onClick

                                (DialogInterface dialog, int which) {
                            OldHouseMapActivity.this.goback();
                        }
                    }).setNegativeButton(getResources().getString

                    (R.string.try_again), new DialogInterface.OnClickListener()

            {
                public void onClick(

                        DialogInterface dialogInterface, int

                        whichButton) {
                    showProgressBar();
                    new Thread(getCacheResultRun).start();
                }
            }).show();
        }
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        isFinish = true;
        super.finish();
    }

    public void goback() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            goback();
            return false;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isFinish) {
                switch (msg.arg1) {
                    case -1:
                        getDataError((String) msg.obj);
                        break;
                    case 0:
                        Toast.makeText(OldHouseMapActivity.this, "抱歉，该区域没有二手房！",
                                Toast.LENGTH_SHORT).show();
                        removeProgressBar();
                        break;
                    case 1:
                        if (msg.arg2 == 1) {
                            addSmallView();
                            removeProgressBar();
                        }
                        break;
                    case 2:
                        getSearchLocationId();
                        break;
                    case 100:
                        new Thread(getOldHouseListResultRun).start();
                        break;
                    case 101:
                        addSmallView();
                        removeProgressBar();
                        new Thread(getOldHouseListResultRun).start();
                        break;
                }
            }
        }
    };

    Runnable getCacheResultRun = new Runnable() {
        @Override
        public void run() {
            if (cacheJson[searchLocationId - 1] == null) {
                cacheJson[searchLocationId - 1] = CacheManager.getCache(
                        OldHouseMapActivity.this, CacheManager.OLD_MAP_CACHE
                                + searchLocationId);
            }
            Message msg = handler.obtainMessage();

            Log.e("JsonString", cacheJson[searchLocationId - 1] + "");
            if (cacheJson[searchLocationId - 1] != null) {
                oldhouseVillageMap = JsonTools
                        .getOldhouseVillageMap(cacheJson[searchLocationId - 1]);
                if (oldhouseVillageMap.getSuccess()) {
                    if (oldhouseVillageMap.getData().size() == 0) {
                        msg.arg1 = 100; // 不显示UI
                    } else {
                        msg.arg1 = 101;
                    }
                } else {
                    msg.arg1 = 100; // 不显示UI
                }
            } else {
                msg.arg1 = 100; // 不显示UI
            }
            handler.sendMessage(msg);
        }
    };
    /**
     * 线程 得到新房列表
     */
    Runnable getOldHouseListResultRun = new Runnable() {

        @Override
        public void run() {
            Message msg = handler.obtainMessage();
            String jsonString;
            int saveLocationId = searchLocationId;
            String url = baseUrl + "?areaid=" + saveLocationId;
            Log.e("yxw", url);
            GalHttpRequest galHttpRequest = new GalHttpRequest(
                    OldHouseMapActivity.this, url);
            galHttpRequest.setCacheEnable(true);
            // jsonString = HttpTools.getJsonContent(url);
            jsonString = galHttpRequest.startSyncRequestString();
            if (isFinish) {
                return;
            }
            Log.e("JsonString", jsonString + "");
            oldhouseVillageMap = JsonTools.getOldhouseVillageMap(jsonString);
            if (oldhouseVillageMap.getSuccess()) {
                if (oldhouseVillageMap.getData().size() == 0) {
                    msg.arg1 = 0;
                } else {
                    if (cacheJson != null
                            && jsonString != null
                            && !jsonString
                            .equals(cacheJson[saveLocationId - 1])) {
                        if (cacheJson[saveLocationId - 1] != null) {
                            msg.arg2 = -1;
                        } else {
                            msg.arg2 = 1;
                        }
                        CacheManager.updateCache(OldHouseMapActivity.this,
                                CacheManager.OLD_MAP_CACHE + saveLocationId,
                                jsonString);
                        msg.arg1 = 1;
                    } else {
                        msg.arg1 = Integer.MAX_VALUE;
                    }
                }
            } else {
                msg.arg1 = -1;
                msg.obj = "连接用户太多，请重试";
            }
            handler.sendMessage(msg);
        }
    };

    Runnable getLocationAddressRun = new Runnable() {

        @Override
        public void run() {
            Message msg = handler.obtainMessage();
            String jsonString;
            String url = AppDataConfig.baiduGeoUrl + "?ak="
                    + AppDataConfig.baiduak + "&callback=renderReverse&"
                    + "location=" + searchLat + "," + searchLng
                    + "&output=json&pois=0";
            Log.e("baidu", url);
            jsonString = HttpTools.getJsonContent(url);
            Log.e("JsonString", jsonString);
            geocoder = JsonTools.getLocationToAddress(jsonString);
            if (geocoder.getStatus() == 0) {
                msg.arg1 = 2;
            } else {
                msg.arg1 = -1;
                msg.obj = geocoder.getErrorMessage();
            }
            handler.sendMessage(msg);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_back:
                // Intent intent=new Intent(this, MainActivity.class);
                // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                // intent.putExtra("TabNo", 0);
                // startActivity(intent);
                this.goback();
                break;
            case R.id.img_my_local:
                testUpdateClick();
                break;
            case R.id.et_search_top:
                // this.goback();
                Intent intent3 = new Intent(OldHouseMapActivity.this,
                        SearchOldHouseActivity.class);
                intent3.putExtra("tabNum", tabNum);
                startActivity(intent3);

                break;
            default:
                break;
        }
    }

    /*
     * 要处理overlay点击事件时需要继承ItemizedOverlay 不处理点击事件时可直接生成ItemizedOverlay.
     */
    class OverlaySmall extends ItemizedOverlay<OverlayItem> {
        // 用MapView构造ItemizedOverlay
        public OverlaySmall(Drawable mark, MapView mapView) {
            super(mark, mapView);
        }

        protected boolean onTap(int index) {
            // OldHouseMapActivity.this.goback();
            // 在此处理item点击事件
            Log.e("yxw", "点击 small item onTap: " + index);
            // 这里通过locationCode放大地图并读取信息
            Intent intent = new Intent(OldHouseMapActivity.this,
                    OldVillageListActivity.class);
            intent.putExtra("villageId", villageId.get(index));
            intent.putExtra("villageName", villageName.get(index) + "");
            intent.putExtra("areaId", searchLocationId);
            startActivity(intent);
            return true;
        }

        public boolean onTap(GeoPoint pt, MapView mapView) {
            // 在此处理MapView的点击事件，当返回 true时
            super.onTap(pt, mapView);
            return false;
        }
    }

    /*
     * 要处理overlay点击事件时需要继承ItemizedOverlay 不处理点击事件时可直接生成ItemizedOverlay.
     */
    class OverlayBig extends ItemizedOverlay<OverlayItem> {
        // 用MapView构造ItemizedOverlay
        public OverlayBig(Drawable mark, MapView mapView) {
            super(mark, mapView);
        }

        protected boolean onTap(int index) {
            // OldHouseMapActivity.this.goback();
            // 在此处理item点击事件
            Log.e("yxw", "点击 big item onTap: " + index);
            isNeedToSmall = false;
            removeAllCircleView();
            setCenter(index + 1);
            mMapView.getController().setZoom(16);
            searchLocationId = index + 1;
            showProgressBar();
            new Thread(getCacheResultRun).start();
            mMapView.refresh();
            return true;
        }

        public boolean onTap(GeoPoint pt, MapView mapView) {
            // 在此处理MapView的点击事件，当返回 true时
            super.onTap(pt, mapView);
            return false;
        }
    }

}
